package com.usts.edu.studenttemp.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.usts.edu.studenttemp.config.SystemVariable;
import com.usts.edu.studenttemp.dto.SysUser;
import com.usts.edu.studenttemp.service.UserService;
import com.usts.edu.studenttemp.utils.ResultResponse;
import com.usts.edu.studenttemp.utils.ResultTypeEnum;
import com.usts.edu.studenttemp.utils.ShiroUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;

/**
 * Created by Guanzhong Hu
 * Date :2020/5/30
 * Description :
 * Version :1.0
 */
@Controller
@RequestMapping("/api/v1/")
public class LoginController extends BaseController {
    @Autowired
    private UserService userService;


    @Autowired
    private Producer producer;

    // 图片验证码
    @RequestMapping("/captcha.jpg")
    public void kaptcha(HttpServletResponse response) throws Exception {

        response.setHeader("Cache-Control", "no-store,no-cache");// 避免浏览器缓存
        response.setContentType("image/jpeg");

        String text = producer.createText();// 验证码
        BufferedImage image = producer.createImage(text);
        //保存session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "jpg", outputStream);// 图片输出
        outputStream.flush();// 清空缓冲区
    }


    //  登录
    @ResponseBody
    @RequestMapping("/user/login")
    public ResultResponse login(SysUser user, String authcode) throws Exception {
        // 验证码不正确
        if (!authcode.equalsIgnoreCase(ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY)))
            return ResultResponse.Build(ResultTypeEnum.fail, "验证码错误！");

        Subject subject = ShiroUtils.getSubject();

        try {
            // 暂不使用加盐加密 todo
            /*String password = new Md5Hash(
                    user.getUserPassword(),
                    user.getUserNumber(),
                    SystemVariable.MD5_HASH_ITERATIONS).toHex();*/

            UsernamePasswordToken token = new UsernamePasswordToken(user.getUserNumber(), user.getUserPassword());

            //记住登录 TODO
            //  token.setRememberMe(true); 暂时不使用记住登录功能

            subject.login(token);

        } catch (IncorrectCredentialsException i) {
            return ResultResponse.Build(ResultTypeEnum.fail, i.getMessage());
        } catch (LockedAccountException l) {
            return ResultResponse.Build(ResultTypeEnum.fail, l.getMessage());
        } catch (AuthenticationException a) {
            return ResultResponse.Build(ResultTypeEnum.fail, "账户验证失败！");
        }

        return ResultResponse.Build(ResultTypeEnum.success, getUser());
    }

    //重置密码
    @RequestMapping("/user/resetpwd")
    @ResponseBody
    public ResultResponse resetPwd(String password) {
        if (StringUtils.isEmpty(getUserId())) {
            return ResultResponse.Build(ResultTypeEnum.fail, "未登录或登录已失效！");
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(getUserId());
        sysUser.setUserPassword(password);
        if (userService.updateUserPassword(sysUser) == SystemVariable.ERROR)
            return ResultResponse.Build(ResultTypeEnum.fail, SystemVariable.DO_ERROR);
        return ResultResponse.Build(ResultTypeEnum.success, SystemVariable.DO_SUCCESS);
    }

    //获取当前用户
    @RequestMapping("/user/getuserinfo")
    @ResponseBody
    public ResultResponse getUserInfo(){
        if (StringUtils.isEmpty(getUserId())) {
            return ResultResponse.Build(ResultTypeEnum.fail, "未登录或登录已失效！");
        }
        return ResultResponse.Build(ResultTypeEnum.success,getUser());
    }

    @RequestMapping("/logout")
    public String logout() {
        // 登出
        ShiroUtils.logout();

        return "redirect:/login.html";
    }
}
